﻿using Org.BouncyCastle.Math.EC;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PressureTest.Main.Device
{
    public partial class DevicePointForm : Form
    {
        /// <summary>模型
        /// 
        /// </summary>
        private DevicePoint obj = new DevicePoint();

        /// <summary>DataGridView
        /// 
        /// </summary>
        private DataGridView dataGridView;

        /// <summary>设备编号
        /// 
        /// </summary>
        public string DeviceNumber = string.Empty;

        /// <summary>设备名称
        /// 
        /// </summary>
        public string DeviceName = string.Empty;

        /// <summary>设备地址
        /// 
        /// </summary>
        public int DeviceAddress;

        /// <summary>刷新界面
        /// 
        /// </summary>
        private void FreshForm()
        {
            this.PointNumberTextBox.Text = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
            PointNameTextBox.Text = "";
            RangeMinTextBox.Text = "";
            RangeMaxTextBox.Text = "";
            OutMinTextBox.Text = "";
            OutMaxTextBox.Text = "";
            UnitTextBox.Text = "";
            SelectComboBox.SelectedIndex = -1;
            AmendTextBox.Text = "";
            AddressTextBox.Text = "";
            AlarmHightTextBox.Text = "";
            AlarmLowTextBox.Text = "";
            ErrorRangeTextBox.Text = "";
            DeviceNumberTextBox.Text = DeviceNumber.ToString();
            DeviceNameTextBox.Text = DeviceName;
            obj = new DevicePoint();
        }

        /// <summary>重复检测
        /// 
        /// </summary>
        /// <returns></returns>
        private bool CheckRepeat()
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["point_name"] = PointNameTextBox.Text;
            where["deviceNumber"] = DeviceNumberTextBox.Text;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            int count = list.Count;
            if (count > 0)
            {
                Alert.Error(where["name"] + "点位已存在");
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>设备点位
        /// 
        /// </summary>
        public void LoadDevicePointList()
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["device_number"] = DeviceNumberTextBox.Text;
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            UpdateDataGridViewRow(list);
            this.HideWaitForm();
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateDataGridViewRow(List<DevicePoint> list)
        {
            if (dataGridView.Rows.Count > 1)
            {
                this.Invoke(new Action(() =>
                {
                    dataGridView.Rows.Clear();
                }));
            }

            foreach (DevicePoint item in list)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.Cells.Add(dataGridViewBoxCell(item.point_number.ToString()));
                row.Cells.Add(dataGridViewBoxCell(item.point_name));
                row.Cells.Add(dataGridViewBoxCell(item.address.ToString()));
                string range = item.rangeMin.ToString() + "-" + item.rangeMax.ToString();
                row.Cells.Add(dataGridViewBoxCell(range));
                string outRange = item.outMin.ToString() + "-" + item.outMax.ToString();
                row.Cells.Add(dataGridViewBoxCell(outRange));
                row.Cells.Add(dataGridViewBoxCell(item.unit));
                row.Cells.Add(dataGridViewBoxCell(item.amend.ToString()));
                string alarm = item.alarm_low.ToString() + "-" + item.alarm_hight.ToString();
                row.Cells.Add(dataGridViewBoxCell(alarm));
                row.Cells.Add(dataGridViewBoxCell(item.error_range.ToString()));
                
                System.Drawing.Color color = System.Drawing.Color.Red;
                string select = "停用";
                if (item.selected == 1)
                {
                    select = "启用";
                    color = System.Drawing.Color.Green;
                }
                row.Cells.Add(dataGridViewBoxCell(select));
                row.DefaultCellStyle.ForeColor = color;
                row.Height = 40;
                this.Invoke(new Action(() =>
                {
                    dataGridView.Rows.Add(row);
                }));

            }
        }

        // <summary> 创建DataGridViewTextBoxCell
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private DataGridViewTextBoxCell dataGridViewBoxCell(string str)
        {
            DataGridViewTextBoxCell cell1 = new DataGridViewTextBoxCell();
            cell1.Value = str;
            return cell1;
        }

        /// <summary>更新obj
        /// 
        /// </summary>
        /// <returns></returns>
        private DevicePoint UpdateObj()
        {
            obj.point_name = PointNameTextBox.Text;
            obj.point_number = PointNumberTextBox.Text.ToInt();
            obj.rangeMin = RangeMinTextBox.Text.ToInt();
            obj.rangeMax = RangeMaxTextBox.Text.ToInt();
            obj.outMin = OutMinTextBox.Text.ToInt();
            obj.outMax = OutMaxTextBox.Text.ToInt();
            obj.unit = UnitTextBox.Text;
            obj.address = AddressTextBox.Text.ToInt();
            obj.device_number = DeviceNumberTextBox.Text.ToInt();
            obj.device_name = DeviceName;
            obj.device_address = DeviceAddress;
            obj.amend = AmendTextBox.Text.ToInt();
            obj.alarm_hight = AlarmHightTextBox.Text.ToInt();
            obj.alarm_low = AlarmLowTextBox.Text.ToInt();
            obj.error_range = ErrorRangeTextBox.Text.ToInt();
            if (SelectComboBox.Text == "启用")
            {
                obj.selected = 1;
            }
            else
            {
                obj.selected = 0;
            }
            return obj;
        }

        public DevicePointForm()
        {
            InitializeComponent();
           
        }

        /// <summary>操作成功
        /// 
        /// </summary>
        private void OperationSuccess()
        {
            Task.Run(() =>
            {
                LoadDevicePointList();
            });
            FreshForm();
        }

        private void DevicePointForm_Load(object sender, EventArgs e)
        {
            this.ShowWaitForm("加载设备");
            this.dataGridView = this.DevicePointDataGridView;
            OperationSuccess();
        }

        private void confirmButton_Click(object sender, EventArgs e)
        {
            if (PointNameTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入点位名称");
                return;
            }

            if (RangeMinTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入点位量程最小值");
                return;
            }

            if (RangeMaxTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入点位量程最大值");
                return;
            }

            if (OutMinTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入点位输出信号最小值");
                return;
            }

            if (OutMaxTextBox.Text.IsNullOrEmpty())
            {
                Alert.Error("请输入点位输出信号最大值");
                return;
            }

            if (obj.device_number > 0)
            {
                if (obj.point_name != PointNameTextBox.Text)
                {
                    bool repeatRes = CheckRepeat();
                    if (repeatRes)
                    {
                        return;
                    }
                }
                UpdateObj();
                List<DevicePoint> list = new List<DevicePoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Updateable<DevicePoint>(list);
                if (res > 0)
                {
                   
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("编辑点位失败");
                }
            }
            else
            {
                bool repeatRes = CheckRepeat();
                if (repeatRes)
                {
                    return;
                }
                UpdateObj();
                List<DevicePoint> list = new List<DevicePoint>();
                list.Add(obj);
                int res = SqlSugarHelper.Insertable(list);
                if (res > 0)
                {
                    OperationSuccess();
                }
                else
                {
                    Alert.Error("添加点位失败");
                }
            }
        }

        /// <summary>刷新
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshButton_Click(object sender, EventArgs e)
        {
            OperationSuccess();
        }

        /// <summary>编辑
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            PointNameTextBox.Text = obj.point_name;
            PointNumberTextBox.Text = obj.point_number.ToString();
            RangeMinTextBox.Text = obj.rangeMin.ToString();
            RangeMaxTextBox.Text = obj.rangeMax.ToString();
            OutMinTextBox.Text = obj.outMin.ToString();
            OutMaxTextBox.Text = obj.outMax.ToString();
            UnitTextBox.Text = obj.unit;
            AddressTextBox.Text = obj.address.ToString();
            AmendTextBox.Text = obj.amend.ToString();
            DeviceNumberTextBox.Text = obj.device_number.ToString();
            DeviceNameTextBox.Text = DeviceName;
            AlarmHightTextBox.Text = obj.alarm_hight.ToString();
            AlarmLowTextBox.Text = obj .alarm_low.ToString();
            ErrorRangeTextBox.Text = obj.error_range.ToString();
            if (obj.selected == 1)
            {
                SelectComboBox.SelectedItem = "启用";
            }
            else
            {
                SelectComboBox.SelectedItem = "停用";
            }
        }

        /// <summary>删除
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeleteMenu_Click(object sender, EventArgs e)
        {
            bool res = CheckSelectedRowExist();
            if (!res)
            {
                return;
            }
            res = this.ShowAskDialog2("友情提示", "您确定要删除吗?", true);
            if (res)
            {
               
                List<DevicePoint> list = new List<DevicePoint>();
                list.Add(obj);
                int deleteRes = SqlSugarHelper.Deleteable(list);
                if (deleteRes > 0)
                {
                    OperationSuccess();
                }
            }
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckSelectedRowExist()
        {
            int number = SelectedRowPrimaryKey();
            obj = RowWithNumber(number);
            if (obj == null)
            {
                Alert.Error("记录不存在");
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>选中记录主键值
        /// 
        /// </summary>
        /// <returns></returns>
        private int SelectedRowPrimaryKey()
        {
            int index = this.dataGridView.CurrentRow.Index;
            return this.dataGridView.Rows[index].Cells[0].Value.ToString().ToInt();
        }

        /// <summary>根据编号查询记录
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private DevicePoint RowWithNumber(int number)
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["point_number"] = number.ToString();
            List<DevicePoint> list = SqlSugarHelper.Inquireable<DevicePoint>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>双击某条记录
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DevicePointDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView.ClearSelection();
            dataGridView.Rows[e.RowIndex].Selected = true;
            dataGridView.CurrentCell = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
            OperationMenu.Show(MousePosition.X, MousePosition.Y);
        }
    }
}
